<template>
  <div class="ml-2 flex-1">
    <div>
      <a-card :bordered="false" style="height: 830px">
        <a-segmented v-model:value="value" :options="data" />
        <div class="card-content mt-3">
          <a-form layout="inline" class="mb-5" :model="searchForm" ref="searchFormRef">
            <a-form-item label="收费期" name="year">
              <a-date-picker v-model:value="searchForm.year" style="width: 130px" picker="year" format="YYYY" />
            </a-form-item>
            <a-form-item label="收费状态" name="chargingStatus" v-if="value !== '查询应收'">
              <a-select v-model:value="searchForm.chargingStatus" placeholder="请选择" style="width: 120px">
                <a-select-option value="待支付">待支付</a-select-option>
                <a-select-option value="部分支付">部分支付</a-select-option>
                <a-select-option value="已支付">已支付</a-select-option>
                <a-select-option value="已全部退款">已全部退款</a-select-option>
                <a-select-option value="退款中">已部分退款</a-select-option>
                <a-select-option value="已部分退款">已部分退款</a-select-option>
                <a-select-option valuue="删除待审批">删除待审批</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="入住状态" name="checkIn">
              <a-select v-model:value="searchForm.checkIn" placeholder="请选择" style="width: 120px">
                <a-select-option value="已入住">已入住</a-select-option>
                <a-select-option value="未入住">未入住</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="供热状态" name="heatingStatus">
              <a-select v-model:value="searchForm.heatingStatus" placeholder="请选择" style="width: 120px">
                <a-select-option value="正常">正常</a-select-option>
                <a-select-option value="报停">报停</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="已生成应收" name="generateHeatFeeStatus" v-if="value !== '查询应收'">
              <a-select v-model:value="searchForm.generateHeatFeeStatus" placeholder="请选择" style="width: 120px">
                <a-select-option value="已生成">已生成</a-select-option>
                <a-select-option value="未生成">未生成</a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onSearch" :icon="h(SearchOutlined)">搜索</a-button>
            </a-form-item>
            <a-form-item>
              <a-button type="primary" @click="onReset">重置</a-button>
            </a-form-item>
          </a-form>
          <a-table size="middle" :columns="columns" :data-source="tableData" rowKey="areaID" :row-selection="{
            selectedRowKeys: selectedRowKeys,
            onChange: onSelectChange,
          }" :row-class-name="(_record: any, index: number) =>
                index % 2 === 1 ? 'table-striped' : null
              " :scroll="{ x: 3000, y: 490 }" :pagination="pagination" bordered :loading="loading"
            style="width: 1350px; height: 560px">
          </a-table>
          <a-card class="mt-12">
            <a-form layout="inline" :model="footerForm" v-if="value !== '查询应收'">
              <a-form-item label="收费期">
                <a-date-picker v-model:value="footerForm.year" style="width: 130px" picker="year" @change="onChangeYear"
                  format="YYYY" />
              </a-form-item>
              <a-form-item label="业务类型">
                <a-select v-model:value="footerForm.businessType" placeholder="请选择" style="width: 150px">
                  <a-select-option value="供热">供热</a-select-option>
                  <a-select-option value="制冷">制冷</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="生成方式">
                <a-select v-model:value="footerForm.generationType" placeholder="请选择" style="width: 150px"
                  @change="onChangeGenerationType">
                  <a-select-option value="正常生成(全费)">正常生成(全费)</a-select-option>
                  <a-select-option value="正常生成(基本费)">正常生成(基本费)</a-select-option>
                  <a-select-option value="按天生成">按天生成</a-select-option>
                  <a-select-option value="计量生成">计量生成</a-select-option>
                  <a-select-option value="协议金额">协议金额</a-select-option>
                  <a-select-option value="协议比例">协议比例</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="计费标准" v-if="
                !['计量生成', '协议金额'].includes(footerForm.generationType)
              ">
                <a-select v-model:value="footerForm.jfbzID" placeholder="请选择" style="width: 120px">
                  <a-select-option v-for="item in chargeStandardList" :key="item.jfbzID" :value="item.jfbzID">{{
                    item.jfbzName }}</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item v-if="value !== '查询应收'">
                <a-button type="primary" block @click="onGenerate">生成应收</a-button>
              </a-form-item>
              <a-form-item v-if="value !== '查询应收'">
                <a-button type="primary" block @click="onQueryGenerate">按查询条件生成应收</a-button>
              </a-form-item>
            </a-form>
            <a-form layout="inline" v-if="value === '查询应收'">
              <a-form-item v-if="value === '查询应收'">
                <a-button type="primary" danger block @click="onDelete">删除应收</a-button>
              </a-form-item>
              <a-form-item v-if="value === '查询应收'">
                <a-button type="primary" danger block @click="onQueryDelete">按查询条件删除应收</a-button>
              </a-form-item>
            </a-form>
          </a-card>
        </div>
      </a-card>
    </div>
    <a-modal v-model:open="isMetering" title="计量生成应收" @ok="() => (isMetering = false)">
      <a-form :model="MeteringForm" :label-col="{ span: 4 }">
        <a-form-item label="基础费" name="meterBaseFee">
          <a-input v-model:value="MeteringForm.meterBaseFee" type="number" style="width: 130px" placeholder="请输入基础费" />
        </a-form-item>
        <a-form-item label="计量用量" name="meterHeat">
          <a-input v-model:value="MeteringForm.meterHeat" type="number" style="width: 130px" placeholder="请输入计量用量" />
        </a-form-item>
        <a-form-item label="计量单价" name="meterPrice">
          <a-input v-model:value="MeteringForm.meterPrice" type="number" style="width: 130px" placeholder="请输入计量单价" />
        </a-form-item>
        <a-form-item label="抹零方式" name="zeroingMethod">
          <a-select v-model:value="MeteringForm.zeroingMethod" placeholder="请选择" style="width: 130px">
            <a-select-option value="不抹零">不抹零</a-select-option>
            <a-select-option value="舍掉尾数">舍掉尾数</a-select-option>
            <a-select-option value="四舍五入">四舍五入</a-select-option>
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="isAgreementRatio" title="协议比例生成应收" @ok="() => (isAgreementRatio = false)">
      <a-form :model="AgreementRatioForm">
        <a-form-item label="协议比例" name="agreementRate">
          <a-input v-model:value="AgreementRatioForm.agreementRate" style="width: 130px" type="number"
            placeholder="请输入协议比例" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal v-model:open="isAgreementAmount" title="协议金额生成应收" @ok="() => (isAgreementAmount = false)">
      <a-form :model="AgreementAmountForm">
        <a-form-item label="协议金额" name="agreementMoney">
          <a-input v-model:value="AgreementAmountForm.agreementMoney" style="width: 130px" type="number"
            placeholder="请输入协议金额" />
        </a-form-item>
      </a-form>
    </a-modal>
    <a-modal title="删除应收" :visible="delModal" @ok="onDelOk" @cancel="delModal = false">
      <a-form :label-col="labelCol" ref="delFormRef">
        <a-form-item label="删除原因">
          <a-textarea v-model:value="delForm.applicationReason" style="width: 200px" placeholder="请输入删除原因" />
        </a-form-item>
        <a-form-item label="附件">
          <a-upload v-model:file-list="fileList" action="https://www.mocky.io/v2/5cc8019d300000980a055e76">
            <a-button>
              <upload-outlined></upload-outlined>
              上传
            </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, h, watch } from 'vue';
import { SearchOutlined, UploadOutlined } from '@ant-design/icons-vue';
import {
  getChargeStandardListApi,
  generateHeatFeeApi,
  searchHeatFeeApi,
  deleteHeatFeeApi,
  deleteHeatFeeByQueryApi,
  searchHeatFee2Api,
} from '#/api/core/charge';
import dayjs from 'dayjs';
import { message } from 'ant-design-vue';
const props = defineProps({
  selectedNodeId: {
    type: Array,
    default: [],
  },
});
const delFormRef = ref(null);
const labelCol = { style: { width: '80px' } };
const data = reactive(['生成应收', '查询应收']);
const value = ref('生成应收');
const searchFormRef = ref<any>(null);
const delModal = ref(false);
const isMetering = ref(false);
const isAgreementRatio = ref(false);
const isAgreementAmount = ref(false);
const loading = ref(false);
const selectedRowKeys = ref<any[]>([]);
const delType = ref('删除');
const delForm = reactive({
  applicationReason: '',
  attachmentLocation: '',
});
const footerForm = reactive({
  year: '',
  generationType: undefined,
  businessType: undefined,
  jfbzID: undefined,
});
const searchForm = reactive({
  year: '',
  chargingStatus: undefined,
  checkIn: undefined,
  heatingStatus: undefined,
  generateHeatFeeStatus: undefined,
});
const MeteringForm = reactive({
  meterBaseFee: '',
  meterHeat: '',
  meterPrice: '',
});
const AgreementRatioForm = reactive({
  agreementRate: '',
});
const AgreementAmountForm = reactive({
  agreementMoney: '',
});
watch(props.selectedNodeId, (newValue) => {
  console.log(newValue);
});
const chargeStandardList = ref<any[]>([]);
const columns = [
  {
    title: '小区名称',
    dataIndex: 'village',
    key: 'village',
    align: 'center',
  },
  {
    title: '用户地址',
    dataIndex: 'houseAddress',
    key: 'houseAddress',
    align: 'center',
  },
  {
    title: '住户姓名',
    dataIndex: 'holder',
    key: 'holder',
    align: 'center',
  },
  {
    title: '热力卡号',
    dataIndex: 'alipayConsNo',
    key: 'alipayConsNo',
    align: 'center',
  },
  {
    title: '收费期',
    dataIndex: 'year',
    key: 'year',
    align: 'center',
  },
  {
    title: '供热状态',
    dataIndex: 'heatingStatus',
    key: 'heatingStatus',
    align: 'center',
  },
  {
    title: '面积名称',
    dataIndex: 'areaName',
    key: 'areaName',
    align: 'center',
  },
  {
    title: '收费面积',
    dataIndex: 'feeArea',
    key: 'feeArea',
    align: 'center',
  },
  {
    title: '生成方式',
    dataIndex: 'generationType',
    key: 'generationType',
    align: 'center',
  },
  {
    title: '业务类型',
    dataIndex: 'businessType',
    key: 'businessType',
    align: 'center',
  },
  {
    title: '单价',
    dataIndex: 'price',
    key: 'price',
    align: 'center',
  },
  {
    title: '应收全费金额',
    dataIndex: 'normalReceivable',
    key: 'normalReceivable',
    align: 'center',
  },
  {
    title: '应收基本费金额',
    dataIndex: 'heatWasteReceivable',
    key: 'heatWasteReceivable',
    align: 'center',
  },
  {
    title: '应收合计金额',
    dataIndex: 'receivableTotal',
    key: 'receivableTotal',
    align: 'center',
  },
  {
    title: '应收减免金额',
    dataIndex: 'receivableDerate',
    key: 'receivableDerate',
    align: 'center',
  },
  {
    title: '优惠合计',
    dataIndex: 'totalDiscountMoney',
    key: 'totalDiscountMoney',
    align: 'center',
  },
  {
    title: '抹零金额',
    dataIndex: 'zeroAmount',
    key: 'zeroAmount',
    align: 'center',
  },
  {
    title: '已收合计',
    dataIndex: 'yjTotal',
    key: 'yjTotal',
    align: 'center',
  },
  {
    title: '实收合计',
    dataIndex: 'realReceiveToal',
    key: 'realReceiveToal',
    align: 'center',
  },
  {
    title: '应退合计',
    dataIndex: 'shouldRefund',
    key: 'shouldRefund',
    align: 'center',
  },
  {
    title: '已退合计',
    dataIndex: 'refundTotal',
    key: 'refundTotal',
    align: 'center',
  },
  {
    title: '应收违约金',
    dataIndex: 'lateFeeRealReceive',
    key: 'lateFeeRealReceive',
    align: 'center',
  },
  {
    title: '违约金减免',
    dataIndex: 'lateFeeDerate',
    key: 'lateFeeDerate',
    align: 'center',
  },
  {
    title: '违约金实收',
    dataIndex: 'lateFeeRealReceive',
    key: 'lateFeeRealReceive',
    align: 'center',
  },
  {
    title: '欠缴热费',
    dataIndex: 'arrearage',
    key: 'arrearage',
    align: 'center',
  },
  {
    title: '欠缴违约金',
    dataIndex: 'arrearageLateFee',
    key: 'arrearageLateFee',
    align: 'center',
  },
  {
    title: '欠费合计',
    dataIndex: 'arrearageTotal',
    key: 'arrearageTotal',
    align: 'center',
  },
];
const tableData = ref<any[]>([]);
// 模拟数据
const mockData = [
  {
    communityName: '小区1',
    userAddress: '地址1',
  },
];
const pagination = reactive({
  total: 0,
  pageSize: 10,
  current: 1,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total: number) => `共 ${total} 条`,
  onChange: (page: number, pageSize: number) => {
    pagination.current = page;
    pagination.pageSize = pageSize;
    onSearch();
  },
});
const onChangeGenerationType = (value: any) => {
  console.log(value);
  if (value === '计量生成') {
    isMetering.value = true;
  } else if (value === '协议比例') {
    isAgreementRatio.value = true;
  } else if (value === '协议金额') {
    isAgreementAmount.value = true;
  }
};
const onChangeYear = (value: any) => {
  console.log(value);
  getChargeStandardListApi(value.$y).then((res) => {
    console.log(res);
    chargeStandardList.value = res;
  });
};
const onGenerate = () => {
  console.log(footerForm);
  const data = {
    headerMessage: {
      year: dayjs(footerForm.year).format('YYYY'),
      businessType: footerForm.businessType,
      generationType: footerForm.generationType,
      jfbzID: footerForm.jfbzID,
      ...MeteringForm,
      ...AgreementRatioForm,
      ...AgreementAmountForm,
    },
    source: '按树选中生成',
    areaIds: selectedRowKeys.value ? selectedRowKeys.value : [],
    treeData: props.selectedNodeId ? props.selectedNodeId : [],
  };
  generateHeatFeeApi(data).then((res) => {
    if (res) {
      message.success(res);
    } else {
      message.error('热费生成失败');
    }
  });
};
const onSearch = () => {
  console.log(props.selectedNodeId);
  if (!props.selectedNodeId||props.selectedNodeId.length === 0) {
    message.error('请选择左侧树结构');
    return;
  } else {
    loading.value = true;
    const data = {
      headerMessage: {
        year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
        chargingStatus: searchForm.chargingStatus,
        checkIn: searchForm.checkIn,
        heatingStatus: searchForm.heatingStatus,
        generateHeatFeeStatus: searchForm.generateHeatFeeStatus,
      },
      treeData: props.selectedNodeId,
      page: pagination.current,
      limit: pagination.pageSize,
    };
    if (value.value === '查询应收') {
      searchHeatFee2Api(data).then((res) => {
        console.log(res);
        pagination.total = res.total;
        tableData.value = res.data;
        loading.value = false;
      });
    } else {
      searchHeatFeeApi(data).then((res) => {
        console.log(res);
        pagination.total = res.total;
        tableData.value = res.data;
        loading.value = false;
      });
    }
  }

};
const onReset = () => {
  console.log(searchForm);
  searchFormRef.value.resetFields();
};
const onQueryGenerate = () => {
  const data = {
    headerMessage: {
      year: footerForm.year ? dayjs(footerForm.year).format('YYYY') : '',
      businessType: footerForm.businessType,
      generationType: footerForm.generationType,
      jfbzID: footerForm.jfbzID,
      ...MeteringForm,
      ...AgreementRatioForm,
      ...AgreementAmountForm,
    },
    source: '按查询结果选择生成',
    areaIds: selectedRowKeys.value ? selectedRowKeys.value : [],
    treeData: props.selectedNodeId ? props.selectedNodeId : [],
  };
  console.log(data);
  generateHeatFeeApi(data).then((res) => {
    if (res) {
      message.success(res);
    } else {
      message.error('热费生成失败');
    }
  });
};
const onDelete = () => {
  // console.log(footerForm);
  delModal.value = true;
  delType.value = '删除';
};
const onDelOk = () => {
  if (delType.value == '删除') {
    deleteHeatFeeByQueryApi({
      treeData: props.selectedNodeId ? props.selectedNodeId.join(',') : '',
      headerMessage: {
        year: searchForm.year ? dayjs(searchForm.year).format('YYYY') : '',
        chargingStatus: searchForm.chargingStatus,
        checkIn: searchForm.checkIn,
        heatingStatus: searchForm.heatingStatus,
        generateHeatFeeStatus: searchForm.generateHeatFeeStatus,
      },
      applicationReason: delForm.applicationReason,
      attachmentLocation: delForm.applicationReason,
    }).then((res) => {
      if (res) {
        message.success(res);
        delModal.value = false;
        delFormRef.value.resetFields();
      } else {
        message.error('热费删除失败');
        delModal.value = false;
        delFormRef.value.resetFields();
      }
    });
  } else {
    // 根据selectedRowKeys.value匹配表格数据中的ysrfID,selectedRowKeys.value为areaID
    const data = tableData.value.filter((item) =>
      selectedRowKeys.value.includes(item.areaID),
    );
    const ysrfIds = data.map((item) => item.ysrfID);
    deleteHeatFeeApi({
      ysrfIds: ysrfIds ? ysrfIds.join(',') : '',
      applicationReason: delForm.applicationReason,
      attachmentLocation: delForm.applicationReason,
    }).then((res) => {
      if (res) {
        message.success(res);
        delModal.value = false;
        delFormRef.value.resetFields();
      } else {
        message.error('热费删除失败');
        delModal.value = false;
        delFormRef.value.resetFields();
      }
    });
  }
};
const onQueryDelete = () => {
  // console.log(selectedRowKeys.value);
  delModal.value = true;
  delType.value = '条件删除';
};
const onSelectChange = (Keys: any[]) => {
  selectedRowKeys.value = Keys;
  console.log(selectedRowKeys.value);
};
</script>
<style scoped>
:deep(.ant-card-body) {
  height: 100%;
}

.card-content {
  height: 100%;
  display: flex;
  flex-direction: column;
}
</style>
